<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ExcelImportTrait;
use App\Helpers\Helpers;
use App\Helpers\Trackingmore;
use App\Model\Express;
use App\Model\ExpressCarrier;
use App\Model\Order;
use App\Model\Resource;
use Hanson\Foundation\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\Console\Helper\Helper;

class ExpressController extends BaseController
{
    use ExcelImportTrait;
    //订单物流单号批量导入模板
    public function exportTemplate()
    {
        $data = ['订单编号','物流公司','物流公司简码','物流单号'];
        $outputName = '订单物流单号批量导入模板-'.date('Ymd');

        return Excel::create($outputName,function ($excel) use($data){
            $excel->sheet('sheet', function($sheet) use($data) {
                $sheet->setWidth(array(
                    'A'     =>  30,
                    'B'     =>  30,
                    'C'     =>  20,
                    'D'     =>  30,
                ));
                $sheet->fromArray($data);
            });
        })->download('xlsx');
    }

    //导出物流运输商
    public function carriersExport()
    {
        $data = ExpressCarrier::orderBy('sort','desc')
            ->select(['name as 英文名称','name_cn as 中文名称','code as 快递简码','phone as 联系电话'])
            ->get()->toArray();
        $outputName = '物流公司-'.date('Ymd');

        return Excel::create($outputName,function ($excel) use($data){
            $excel->sheet('sheet', function($sheet) use($data) {
                $sheet->fromArray($data);
            });
        })->download('xlsx');
    }

    //更新获取运输商
    public function updateCarrierList()
    {
        $model = new Trackingmore();
        $res = $model->getCarrierList();
        if ($res && isset($res['meta']) && $res['meta']['code'] == 200){
            $items = $res['data'];
            $c = count($items);
            for ($i=0;$i<$c;$i++){
                ExpressCarrier::updateOrCreate(['code'=>$items[$i]['code']],$items[$i]);
            }
        }
        return $this->success(['count'=>$c]);
    }

    //导入
    public function import(Request $request)
    {

        $file = $request->file('file');
        $resource = Resource::saveUploadFile($file,'local');

        $items = $this->load($file)->toArray();

        $header = $items[0];

        $check  = false;
        if ($header[0] == "订单编号" && $header[1] == "物流公司" && $header[2] == "物流公司简码" && $header[3] == "物流单号") {
            $check = true;
        }

        if (!$check) {
            return $this->failed('模板错误');
        }

        unset($items[0]);

        $total = count($items); //总记录
        $MultipleTracking = []; //创建批量物流API调用接口数组
        $errors = []; //错误
        $s = 0; //成功数量
        $e = 0; //错误数量
        for ($i=1;$i<=$total;$i++) {
            try
            {
                $c = Express::where('out_trade_no','=',$items[$i][0])
                    ->where('tracking_number','=',$items[$i][3])
                    ->where('carrier_code','=',$items[$i][2])
                    ->count();

                if ($c >0) {
                    $errors[] = "#".$items[$i][0].' 已存在该物流记录';
                    continue;
                }else{
                    $e = Express::firstOrNew(['out_trade_no'=>$items[$i][0],'tracking_number'=>$items[$i][3],'carrier_code'=>$items[$i][2]]);

                    //查找订单
                    $order = Order::findByOutTradeNo($items[$i][0]);
                    if (!$order) {
                        $errors[] = "#".$items[$i][0].' 订单不存在';
                        $e++;
                        continue;
                    }

                    //确定状态是否为待发货
                    if ($order->state != 1) {
                        $errors[] = "#".$items[$i][0].' 订单不是待发货状态';
                        $e++;
                        continue;
                    }

                    $e->order_id = $order->id;
                    $e->title = $order->product_chname?$order->product_chname:'';
                    $e->customer_name = $order->username?$order->username:'';

                    if($e->save()){

                        ExpressCarrier::addSort($items[$i][2]);


                        //生成物流记录成功标记状态为已发货
                        $order->is_delivery = "yes";
                        $order->delivery_time = date('Y-m-d H:i:s');
                        $order->state = 5;
                        $order->save();

                        //存入创建批量物流API调用接口数组
                        $MultipleTracking[$e->id] = [
                            'tracking_number'=>$e->tracking_number,
                            'carrier_code'=>$e->carrier_code,
                            'title'=>$e->title,
                            'customer_name'=>$e->customer_name,
                            'customer_email'=>$e->customer_email,
                            'order_id'=>$e->out_trade_no
                        ];
                        $s++;
                    }
                }
            }catch (\Exception $err) {
                Helpers::log($err->getMessage(),'import_err');
            }

        }

        $submitted = 0;
        $added = 0;
        if(!empty($MultipleTracking)) {
            $track = new Trackingmore();
            $res = $track->createMultipleTracking($MultipleTracking);

            if ($res && $res['meta']['code'] == 200) {
                $added = $res['data']['added'];
                $submitted = $res['data']['submitted'];
                $trackings = $res['data']['trackings'];

                foreach ($trackings as $t){
                    DB::table('order_expresses')->where('out_trade_no','=',$t['out_trade_no'])
                        ->where('tracking_number','=',$t['tracking_number'])
                        ->where('carrier_code','=',$t['carrier_code'])
                        ->update(['tracking_id'=>$t['id'],'status'=>$t['status']]);
                }
            }

            Helpers::log(json_encode($res),'createMultipleTracking');
        }

        return $this->success(['total'=>$total,'success'=>$s,'errors'=>$errors,'submitted'=>$submitted,'added'=>$added]);

    }

}
